package com.study.jdbc.proxy.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.junit.Test;

/**
* @Name: Client
* @Description: JDK动态代理测试类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-18 下午3:34:20 
* @Version: V1.0
 */
public class Client {
	
	
	@Test
	public void noProxy() {
		SpringBrother brother = new SpringBrother() ;
		brother.sing(1000) ;
		brother.dance(1000) ;
		brother.eat() ;
	}
	
	/**
	* @Name: cglibProxy
	* @Description: 使用CGLIB动态代理：直接代理目标类，代理类为目标类的子类，即基于子类的动态代理
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-18 下午3:36:01
	* @Parameters: 
	* @Return: void
	 */
	@Test
	public void cglibProxy() {
		final SpringBrother brother = new SpringBrother() ;
		SpringBrother proxy = (SpringBrother) Enhancer.create(SpringBrother.class, new MethodInterceptor() {
			@Override
			public Object intercept(Object proxy, Method method, Object[] args,
					MethodProxy methodproxy) throws Throwable {
				//声明方法执行的返回值
				Object result = null ;
				Float money = null ;
				//接收方法实参
				if(args != null && args.length > 0) {
					money = (Float) args[0] ;
				}
				if("sing".equals(method.getName())) {
					if(money > 100) {
						result = method.invoke(brother, args) ;
					} else {
						System.out.println("钱不够(最少100)，不能唱歌！");
					}
				} 
				if("dance".equals(method.getName())) {
					if(money > 1000) {
						result = method.invoke(brother, args) ;
					} else {
						System.out.println("钱不够(最少1000)，不能跳舞！");
					}
				} 
				if("eat".equals(method.getName())) {
					result = method.invoke(brother, args) ;
				}
				return result ;
			}
		}) ;
		//代理执行接口实现类的方法
		proxy.sing(12) ;
		proxy.dance(2000) ;
		proxy.eat() ;
	}
	
}











